package com.urbane.auth.controller;

import com.urbane.auth.dto.LoginRequest;
import com.urbane.auth.vo.LoginResponse;
import com.urbane.auth.dto.RefreshTokenRequest;
import com.urbane.auth.dto.RegisterRequest;
import com.urbane.auth.service.AuthService;
import com.urbane.auth.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器（认证相关接口）
 * 路径前缀：/auth
 * 功能：
 *   - /login：用户登录，返回 JWT Token
 *   - /register：用户注册，发送激活邮件
 *   - /logout：用户登出，将 Token 加入黑名单
 *   - /refresh-token：使用旧 Token 换取新 Token
 * <p>
 * 注意：
 *   - 所有接口均无需认证（由 WebSecurityConfig 允许匿名访问）
 *   - 所有输入需校验（@Valid）
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final TokenService tokenService;

    @PostMapping("/logout")
    public String logout() {
        return "Logout successful";
    }

    @PostMapping("/refresh-token")
    public String refreshToken() {
        return "Token refreshed successfully";
    }

    /**
     * 用户登录
     * 请求：POST /auth/login
     * 输入：{ username: "zhangsan", password: "123456" }
     * 输出：{ token: "eyJ...", user: { id, username, avatar } }
     */
    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        LoginResponse response = authService.login(request);
        return ResponseEntity.ok(response);
    }

    /**
     * 用户注册
     * 请求：POST /auth/register
     * 输入：{ username: "lisi", email: "lisi@example.com", password: "abc123" }
     * 输出：{ success: true }
     *
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<Boolean> register(@Valid @RequestBody RegisterRequest request) {
        Boolean result = authService.register(request);
        return ResponseEntity.ok(result);
    }

    /**
     * 刷新 Token（无感续期）
     * 请求：POST /auth/refresh-token
     * 输入：{ token: "旧的JWT" }
     * 输出：{ token: "新的JWT" }
     */
    @PostMapping("/refresh-token")
    public ResponseEntity<LoginResponse> refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
        LoginResponse response = authService.refreshToken(request.getToken());
        return ResponseEntity.ok(response);
    }

    /**
     * 用户登出
     * 请求：POST /auth/logout
     * Header：Authorization: Bearer <token>
     * 输出：{ success: true }
     */
    @PostMapping("/logout")
    public void logout(@RequestHeader("Authorization") String authorization) {
        String token = authorization.substring(7); // 移除 "Bearer "
        tokenService.blacklistToken(token);
    }

    @GetMapping("/oauth2/authorization/github")
    public String githubAuth (HttpServletRequest request) {
        return "index";
    }

    @GetMapping("/oauth2/authorization/gitee")
    public String giteebAuth (HttpServletRequest request) {
        return "index";
    }


    @GetMapping("/auth/oauth2/code/github/callback")
    public String github(
            @RequestParam("code") String code,
            @RequestParam(value = "state", required = false) String state) {

        // 处理code和state
        System.out.println("Received code: " + code);
        System.out.println("Received state: " + state);

        // 这里你可以使用code去换取访问令牌
        // 例如调用exchangeForAccessToken(code)

        return "redirect:/index";
    }
}
